import { NextResponse } from 'next/server';
import moment from 'moment';
import prisma from '@/lib/prisma';
const tencentcloud = require("tencentcloud-sdk-nodejs-asr");

const COS = require('cos-nodejs-sdk-v5');

const cos = new COS({
  SecretId: process.env.TENCENT_SECRET_ID,
  SecretKey: process.env.TENCENT_SECRET_KEY,
});
const AsrClient = tencentcloud.asr.v20190614.Client;

// 初始化客户端配置
const clientConfig = {
  credential: {
    secretId: process.env.TENCENT_SECRET_ID,
    secretKey: process.env.TENCENT_SECRET_KEY,
  },
  region: "ap-shanghai",
  profile: {
    httpProfile: {
      endpoint: "asr.tencentcloudapi.com",
    },
  },
};

const client = new AsrClient(clientConfig);


// 查询识别结果
export async function GET(
  request: Request,
  { params }: { params: { id: string } }
) {
    try {
      const { id } = params;

      // 通过id获取vms_asr记录
      const vmsAsr = await prisma.vms_asr.findUnique({
        where: { id: id}
      });

      if (!vmsAsr || !vmsAsr.task_id) {
        return NextResponse.json(
          { error: "Task ID not found for the given subtitle ID" },
          { status: 404 }
        );
      }

      const taskId = vmsAsr.task_id.toString();
      const requestParams = {
        TaskId: Number(taskId),
      };
  
      // 增加对ASR请求的异常处理
      let data;
      try {
        data = await client.DescribeTaskStatus(requestParams);
        // console.log("ASR API Response Data:", data);
      } catch (error) {
        console.error("ASR API Error:", error);
        
        return NextResponse.json(
          { 
            error: "Failed to fetch task status from ASR API",
            details: error instanceof Error ? error.message : "Unknown ASR API error"
          },
          { status: 500 }
        );
      }

    //   console.log(data)
     
        // 提取字幕内容
        let subtitleText = '';
        
        // 检查是否有有效的字幕数据
        if (data.Data && data.Data.Result) {
          if (Array.isArray(data.Data.Result) && data.Data.Result.length > 0) {
            subtitleText = data.Data.Result
              .map((s: any, i: number) => {
                try {
                  // 确保输入是字符串
                  if (typeof s !== 'string') {
                    console.warn(`Invalid subtitle format at index ${i}:`, s);
                    return '';
                  }
                  
                  // 提取时间戳
                  const timeSegment = s.match(/\[([\d.,]+)\]/);
                  if (!timeSegment) {
                    console.warn(`Invalid time format at index ${i}:`, s);
                    return '';
                  }
                  
                  // 解析开始和结束时间
                  const [start, end] = timeSegment[1].split(',');
                  const startMs = parseFloat(start) * 1000;
                  const endMs = parseFloat(end) * 1000;
                  
                  // 提取文本内容并去除时间戳部分
                  const textContent = s.split(']')[1]?.trim() || '';
                  const cleanText = textContent.replace(/\[\d+:\d+\.\d+,\d+:\d+\.\d+,\d+\]\s*/g, '');
                  
                  // 格式化SRT内容
                  const startTime = moment(startMs).format('HH:mm:ss,SSS');
                  const endTime = moment(endMs).format('HH:mm:ss,SSS');
                  
                  // 处理多行文本
                  const formattedText = cleanText
                    .split('\n')
                    .map(line => line.trim())
                    .filter(Boolean)
                    .join('\n');
                  
                  return `${i + 1}\n${startTime} --> ${endTime}\n${formattedText}`;
                } catch (error) {
                  console.error(`Error processing subtitle at index ${i}:`, error);
                  return '';
                }
              })
              .filter(Boolean) // 过滤空条目
              .join('\n\n');
          } else if (typeof data.Data.Result === 'string' && data.Data.Result.trim() !== '') {
            // 处理纯字符串结果
            subtitleText = data.Data.Result
              .split('\n')
              .map((line: string, i: number) => {
                const startTime = moment(i * 1000).format('HH:mm:ss,SSS');
                const endTime = moment((i + 1) * 1000).format('HH:mm:ss,SSS');
                const cleanLine = line.replace(/\[\d+:\d+\.\d+,\d+:\d+\.\d+,\d+\]\s*/g, '');
                return `${i + 1}\n${startTime} --> ${endTime}\n${cleanLine.trim()}`;
              })
              .join('\n\n');
          }
        }

        // 如果提取的内容为空，返回错误
        if (!subtitleText.trim()) {
          return NextResponse.json(
            { 
              error: "Empty subtitle content",
              details: "The subtitle content is empty or invalid"
            },
            { status: 404 }
          );
        }

        // 打印提取的字幕内容
        console.log("Extracted subtitle text:", subtitleText);

        // 更新字幕内容和状态
        try {
          const updatedVmsAsr = await prisma.vms_asr.update({
            where: { id: vmsAsr.id },
            data: {
              subtitle_text: subtitleText,
              status: "1"
            }
          });
          
             // 删除COS文件
          if (vmsAsr.filekey) {
            try {
              await new Promise((resolve, reject) => {
                cos.deleteObject({
                  Bucket: process.env.TENCENT_COS_BUCKET,
                  Region: process.env.TENCENT_COS_REGION,
                  Key: vmsAsr.filekey,
                }, function(err: Error, data: any) {
                  if (err) reject(err);
                  else resolve(data);
                });
              });
              console.log(`Successfully deleted COS file: ${vmsAsr.filekey}`);
            } catch (deleteError) {
              console.error(`Failed to delete COS file: ${vmsAsr.filekey}`, deleteError);
              // 文件删除失败不影响主流程，继续返回成功
            }
          }

          return NextResponse.json({
            ...updatedVmsAsr,
            id: updatedVmsAsr.id.toString(),
            task_id: updatedVmsAsr.task_id?.toString()
          });
        } catch (dbError) {
          console.error("Database update error:", dbError);
          return NextResponse.json(
            { 
              error: "Failed to update subtitle in database",
              details: dbError instanceof Error ? dbError.message : "Unknown database error"
            },
            { status: 500 }
          );
        }
 
      
    } catch (error) {
      console.error("Error getting task status:", error);
      return NextResponse.json(
        { 
          error: "Failed to get task status",
          details: error instanceof Error ? error.message : "Unknown error"
        },
        { status: 500 }
      );
    }
  }